<template>
  <el-form label-width="120px" :model="skuInfo" :rules="rules" ref="ruleFormRef">
    <el-form-item label="SPU名称"><p>123456</p></el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="请输入SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
       <el-input placeholder="" v-model="skuInfo.price"></el-input>
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
       <el-input placeholder="" v-model="skuInfo.weight"></el-input>
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea"  v-model="skuInfo.skuDesc"/>
    </el-form-item>
    <el-form-item label="平台属性" :inline='true'  class="demo-form-inline" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="(attrData,index) in attrList" :key="attrData.id" :span="12" :xs="10" :sm="8" :md="7" :lg="9" :xl="3" ><div class="grid-content ep-bg-purple" />
         <el-form-item :label="attrData.attrName" style="margin-bottom:20px">
            <el-select placeholder="请选择" v-model="skuInfo.skuAttrValueList[index]" @change="clearAttrRules(skuAttrValueList)">
              <el-option v-for="attrValue in attrData.attrValueList" :key="attrValue.id" :label="attrValue.valueName" 
              :value="`${attrData.id}:${attrData.attrName}:${attrValue.id}:${attrValue.valueName}`"  />
               <!-- <el-option v-for="attrValue in attrData.attrValueList" :key="attrValue.id" :label="attrValue.valueName" 
              :value="{'attrId':attrData.id,'attrName':attrData.attrName,'valueId':attrValue.id,'valueName':attrValue.valueName}"  /> -->
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" :inline='true'  class="demo-form-inline" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="(saleList,index) in spuSaleAttrList" :key="saleList.id" :span="12" :xs="10" :sm="8" :md="7" :lg="9" :xl="3"><div class="grid-content ep-bg-purple" />
         <el-form-item :label="saleList.saleAttrName">
            <el-select placeholder="请选择" v-model="skuInfo.skuSaleAttrValueList[index]" @change="clearAttrRules(skuSaleAttrValueList)">
              <el-option v-for="saleValue in saleList.spuSaleAttrValueList" :key="saleValue.id" :label="saleValue.saleAttrValueName" 
              :value="`${saleList.id}:${saleList.saleAttrName}:${saleValue.id}:${saleValue.saleAttrValueName}`" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table border :data="spuImageList"  @selection-change="handleSelectionChange">
        <el-table-column type="selection">
        </el-table-column>
        <el-table-column label="图片" align="center">
          <template v-slot="{row}">
            <el-image :src="row.imgUrl" :alt="row.imgName" style="width:120px;height:120px"></el-image>
          </template> 
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button type="primary"  v-if="row.isDefault == 0" @click="setButton(row)">设置默认</el-button>
            <el-button v-else>默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang='ts'>
export default {
  name: "SkuForm",
};
</script>
<script lang="ts" setup>
import {onMounted,reactive,ref} from 'vue'
import {reqGetAttrListDataByCategory3Id} from '@/api/product/attr'
import {reqGetSpuImageListData,reqGetSpuSaleAttrListData} from '@/api/product/spu'
import {reqSaveSkuInfo} from '@/api/product/sku'
import {useCategoryListStore} from '@/stores/categoryList'
import {typeSpu} from '../type'
import type { FormInstance, FormRules } from 'element-plus'
import {ElMessage} from 'element-plus'
// 拿到store里面的数据
const categoryStore = useCategoryListStore()
// 接收参数
const props = defineProps(['currentSpuInfo'])
const spuImageList = ref([])
const spuSaleAttrList = ref([])
const attrList = ref([])

// 表单校验
const ruleFormRef = ref<FormInstance>()
// 书写自定义规则
const skuAttrValueListValidate = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    return callback('至少选择一个平台属性')
  }
    callback()
  
}
const skuImageListValidate = (rule: any, value: any, callback: any) => {
  if(!value.length){
    return callback('请至少上传一张图片')
  }
    callback()
}
const skuSaleAttrValueListValidate = (rule: any, value: any, callback: any) => {
   if (!value.length) {
    return callback('至少选择一个销售属性')
  }
    callback()
}
const rules = reactive<FormRules>({
  skuName: [
    {required: true, message: 'q请输入sku名称', trigger: 'blur'},
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },],
  price:[{required: true, message: '请输入价格', trigger: 'change'}],
  weight:[{required: true, message: '请输入体重', trigger: 'change'}],
  skuDesc: [{required: true, message: '请输入sKu描述', trigger: 'blur'}],
  skuAttrValueList: [{required: true,validator:skuAttrValueListValidate, trigger: 'change'}],
  skuImageList: [{required: true, validator:skuImageListValidate, trigger: 'change'}],
  skuSaleAttrValueList: [{required: true, validator:skuSaleAttrValueListValidate, trigger: 'change'}],
})

// 设置skuInfo列表数据
const skuInfo = reactive({
    // spu名称
  skuName: '',
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: '',
  // 默认图片
  skuDefaultImg: '',
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: []
})
// 自定义事件传递参数
const emit = defineEmits(['setshowSpu'])
//1.品牌，属性，图片同时发送请求
onMounted(async() => {
  let [getAttrListDataByCategory3Id,getSpuImageListData,getSpuSaleAttrListData] = await Promise.allSettled([
    reqGetAttrListDataByCategory3Id({
      category1Id:categoryStore.category1Id,
      category2Id:categoryStore.category2Id,
      category3Id:categoryStore.category3Id
      }
    ),reqGetSpuImageListData(props.currentSpuInfo.id),reqGetSpuSaleAttrListData(props.currentSpuInfo.id)
  ])
  attrList.value = getAttrListDataByCategory3Id.value;
  spuSaleAttrList.value = getSpuSaleAttrListData.value;
  if(getSpuImageListData ?.status === 'fulfilled'){
     spuImageList.value = getSpuImageListData.value.map(item =>{
      return{
          ...item,
          isDefault:0
      }
     })
  }
});
// 2.取消当前页面，返回上一层
const cancle = ()=>{
  emit('setshowSpu',typeSpu.SPU_LIST)
}

// 3.点击设置按钮显示默认
const setButton = (row)=>{
  spuImageList.value.forEach(item =>{
    item.isDefault = 0
  })
  row.isDefault = 1
  // 获取图片的默认地址
  skuInfo.skuDefaultImg = row.imgUrl
}

// 4.选取图片的时候收集图片
const handleSelectionChange = (val) => {
  // console.log(val);
  skuInfo.skuImageList = val
}
// 5.提交表单
const submitForm =async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
   
    if (valid) {
      // 4.3判断一下选的那些图片中是否有默认图片(放到前面，解决item.split不是一个函数的问题，是因为刚开始没有设置默认图片的时候，已经对数据字符串转化成了数组，再次提交的时候数组不存在split方法)
      let flag = skuInfo.skuImageList.every(item => item.isDefault === 0)
      if(flag){
        ElMessage.warning('请在选择的图片中设置一个默认图片');
          return;
      }
      // 4.1过滤掉空平台属性和销售属性,处理格式，将字符串变为对象
      // 空平台属性
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map(item => {
        const [attrId,attrName,valueId,valueName] = item ?.split(':')
        return{
          attrId,attrName,valueId,valueName
        }
      })
      // 空销售属性
     skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item => {
      const [saleAttrId,saleAttrName,saleAttrValueId,saleAttrValueName] = item ?.split(':')
      return{
        saleAttrId,saleAttrName,saleAttrValueId,saleAttrValueName
      }
     })
    //  4.2添加对应的spuId和category3Id
     skuInfo.spuId = props.currentSpuInfo.id
     skuInfo.category3Id = categoryStore.category3Id as number
   
   //4.4请求添加数据,发送请求
    const result =  await reqSaveSkuInfo(skuInfo)
    console.log('rrrrr',result);
    // 4.5提示
    ElMessage.success('添加Sku成功...')

    //4.6 跳转到列表页
    emit('setshowSpu',typeSpu.SPU_LIST)
    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 6.清除校验
const clearAttrRules = (val)=>{
  ruleFormRef?.value?.clearValidate(val)
}
</script>
<style scoped>
</style>